/**
 * 数据管理器
 * 处理本地缓存和云端同步
 */
class DataManager {
    constructor() {
        this.cache = new Map();
        this.eventListeners = new Map();
        this.syncStatus = {
            syncing: false,
            lastSync: null,
            success: true,
            message: ''
        };
    }
    
    /**
     * 初始化数据管理器
     */
    async initialize() {
        try {
            // 初始化Gitee API
            await window.giteeAPI.initialize();
            
            // 加载本地缓存
            this.loadLocalCache();
            
            // 尝试从云端同步数据
            await this.syncFromCloud();
            
            return { success: true };
        } catch (error) {
            console.error('数据管理器初始化失败:', error);
            return { success: false, message: error.message };
        }
    }
    
    /**
     * 加载本地缓存
     */
    loadLocalCache() {
        const cacheKeys = ['demands', 'workflows', 'demandTypes', 'urgencyLevels', 'users', 'config'];
        
        cacheKeys.forEach(key => {
            const data = localStorage.getItem(`tasktrack_${key}`);
            if (data) {
                try {
                    this.cache.set(key, JSON.parse(data));
                } catch (error) {
                    console.error(`解析本地缓存 ${key} 失败:`, error);
                }
            }
        });
    }
    
    /**
     * 保存到本地缓存
     */
    saveToCache(key, data) {
        this.cache.set(key, data);
        localStorage.setItem(`tasktrack_${key}`, JSON.stringify(data));
    }
    
    /**
     * 从缓存加载数据
     */
    loadFromCache(key) {
        return this.cache.get(key);
    }
    
    /**
     * 从云端同步数据
     */
    async syncFromCloud() {
        if (!window.giteeAPI.isConfigured()) {
            console.log('Gitee未配置，使用本地默认数据');
            this.loadDefaultData();
            return { success: true, message: '使用本地默认数据' };
        }
        
        try {
            this.setSyncStatus(true, '正在同步数据...');
            
            const dataFiles = [
                { key: 'demands', path: 'data/demands.json' },
                { key: 'workflows', path: 'data/workflows.json' },
                { key: 'demandTypes', path: 'data/demand-types.json' },
                { key: 'urgencyLevels', path: 'data/urgency-levels.json' },
                { key: 'users', path: 'data/users.json' },
                { key: 'config', path: 'data/config.json' }
            ];
            
            for (const file of dataFiles) {
                try {
                    const result = await window.giteeAPI.getFile(file.path);
                    if (result.success) {
                        this.saveToCache(file.key, result.data);
                    }
                } catch (error) {
                    console.warn(`同步 ${file.path} 失败:`, error);
                    // 如果文件不存在或其他错误，使用默认数据
                    const defaultData = this.getDefaultData(file.key);
                    if (defaultData) {
                        this.saveToCache(file.key, defaultData);
                    }
                }
            }
            
            this.setSyncStatus(false, '同步完成', true);
            return { success: true };
        } catch (error) {
            console.error('云端同步失败:', error);
            this.setSyncStatus(false, error.message, false);
            // 同步失败时使用默认数据
            this.loadDefaultData();
            return { success: false, message: error.message };
        }
    }
    
    /**
     * 加载默认数据到缓存
     */
    loadDefaultData() {
        const defaultData = {
            demands: this.getDefaultData('demands'),
            workflows: this.getDefaultData('workflows'),
            demandTypes: this.getDefaultData('demandTypes'),
            urgencyLevels: this.getDefaultData('urgencyLevels'),
            users: this.getDefaultData('users'),
            config: this.getDefaultData('config')
        };
        
        Object.entries(defaultData).forEach(([key, data]) => {
            if (data && !this.cache.has(key)) {
                this.saveToCache(key, data);
            }
        });
    }
    
    /**
     * 获取默认数据
     */
    getDefaultData(key) {
        const defaults = {
            demands: [],
            workflows: {
                "new_product": {
                    "id": "new_product",
                    "name": "新品上架",
                    "description": "新产品从需求提出到最终上架的完整流程",
                    "demandType": "new_product",
                    "nodes": [
                        {
                            "id": "submit",
                            "name": "需求提出",
                            "description": "运营人员提出新品上架需求",
                            "defaultAssignee": null,
                            "order": 1
                        },
                        {
                            "id": "product_review",
                            "name": "产品评估",
                            "description": "产品团队评估新品可行性",
                            "defaultAssignee": "product_manager",
                            "order": 2
                        },
                        {
                            "id": "planning",
                            "name": "计划制定",
                            "description": "制定详细的上架计划和时间安排",
                            "defaultAssignee": "planning_specialist",
                            "order": 3
                        },
                        {
                            "id": "execution",
                            "name": "执行跟进",
                            "description": "执行上架计划并跟进进度",
                            "defaultAssignee": "execution_manager",
                            "order": 4
                        }
                    ]
                }
            },
            demandTypes: {
                "new_product": {
                    "name": "新品上架",
                    "color": "#007bff",
                    "icon": "🛍️",
                    "enabled": true,
                    "workflowTemplate": "new_product"
                },
                "promotion": {
                    "name": "促销活动",
                    "color": "#28a745",
                    "icon": "🎉",
                    "enabled": true,
                    "workflowTemplate": "promotion"
                },
                "inventory": {
                    "name": "库存补充",
                    "color": "#ffc107",
                    "icon": "📦",
                    "enabled": true,
                    "workflowTemplate": "inventory"
                },
                "price_adjust": {
                    "name": "价格调整",
                    "color": "#dc3545",
                    "icon": "💰",
                    "enabled": true,
                    "workflowTemplate": "price_adjust"
                }
            },
            urgencyLevels: [
                { "id": 1, "name": "低", "color": "#6c757d", "priority": 1, "days": 999 },
                { "id": 2, "name": "正常", "color": "#28a745", "priority": 2, "days": 15 },
                { "id": 3, "name": "重要", "color": "#ffc107", "priority": 3, "days": 7 },
                { "id": 4, "name": "紧急", "color": "#dc3545", "priority": 4, "days": 3 }
            ],
            users: [
                {
                    "id": "admin",
                    "username": "admin",
                    "password": "zxc123456",
                    "name": "系统管理员",
                    "email": "admin@company.com",
                    "roles": ["管理员"],
                    "permissions": {
                        "createDemand": true,
                        "editDemand": true,
                        "deleteDemand": true,
                        "viewAllDemands": true,
                        "configureWorkflow": true,
                        "markComplete": true,
                        "addSignNode": true,
                        "manageUsers": true,
                        "systemSettings": true
                    },
                    "createdAt": "2023-12-01T00:00:00.000Z",
                    "lastLogin": null,
                    "isActive": true
                }
            ],
            config: {
                "version": "2.0.0",
                "lastUpdated": new Date().toISOString()
            }
        };
        
        return defaults[key];
    }
    
    /**
     * 保存到Gitee
     */
    async saveToGitee(path, data) {
        if (!window.giteeAPI.isConfigured()) {
            console.warn('Gitee未配置，跳过云端保存');
            return { success: false, message: 'Gitee未配置' };
        }
        
        try {
            const result = await window.giteeAPI.saveFile(path, data, `更新 ${path}`);
            return result;
        } catch (error) {
            console.error(`保存到Gitee ${path} 失败:`, error);
            return { success: false, message: error.message };
        }
    }
    
    /**
     * 设置同步状态
     */
    setSyncStatus(syncing, message = '', success = true) {
        this.syncStatus = {
            syncing,
            lastSync: syncing ? null : new Date().toISOString(),
            success,
            message
        };
        
        this.emit('syncStatusChanged', this.syncStatus);
    }
    
    /**
     * 获取需求列表
     */
    async getDemands() {
        let demands = this.loadFromCache('demands');
        if (!demands) {
            demands = await this.loadFromGitee('data/demands.json') || [];
            this.saveToCache('demands', demands);
        }
        return demands;
    }
    
    /**
     * 添加需求
     */
    async addDemand(demand) {
        try {
            const demands = await this.getDemands();
            
            // 生成ID
            if (!demand.id) {
                demand.id = `demand_${Date.now()}`;
            }
            
            // 设置创建时间
            demand.createdAt = new Date().toISOString();
            demand.updatedAt = demand.createdAt;
            
            demands.push(demand);
            
            const result = await this.saveToGitee('data/demands.json', demands);
            if (result.success) {
                this.saveToCache('demands', demands);
                this.emit('dataChanged', { type: 'demands', data: demands });
            }
            
            return result;
        } catch (error) {
            console.error('添加需求失败:', error);
            return { success: false, message: error.message };
        }
    }
    
    /**
     * 更新需求
     */
    async updateDemand(updatedDemand) {
        try {
            const demands = await this.getDemands();
            const index = demands.findIndex(d => d.id === updatedDemand.id);
            
            if (index === -1) {
                return { success: false, message: '需求不存在' };
            }
            
            updatedDemand.updatedAt = new Date().toISOString();
            demands[index] = { ...demands[index], ...updatedDemand };
            
            const result = await this.saveToGitee('data/demands.json', demands);
            if (result.success) {
                this.saveToCache('demands', demands);
                this.emit('dataChanged', { type: 'demands', data: demands });
            }
            
            return result;
        } catch (error) {
            console.error('更新需求失败:', error);
            return { success: false, message: error.message };
        }
    }
    
    /**
     * 删除需求
     */
    async deleteDemand(demandId) {
        try {
            const demands = await this.getDemands();
            const filteredDemands = demands.filter(d => d.id !== demandId);
            
            if (filteredDemands.length === demands.length) {
                return { success: false, message: '需求不存在' };
            }
            
            const result = await this.saveToGitee('data/demands.json', filteredDemands);
            if (result.success) {
                this.saveToCache('demands', filteredDemands);
                this.emit('dataChanged', { type: 'demands', data: filteredDemands });
            }
            
            return result;
        } catch (error) {
            console.error('删除需求失败:', error);
            return { success: false, message: error.message };
        }
    }
    
    /**
     * 获取流程配置
     */
    async getWorkflows() {
        let workflows = this.loadFromCache('workflows');
        if (!workflows) {
            workflows = await this.loadFromGitee('data/workflows.json') || this.getDefaultData('workflows');
            this.saveToCache('workflows', workflows);
        }
        return workflows;
    }
    
    /**
     * 保存流程配置
     */
    async saveWorkflow(workflowId, workflow) {
        try {
            const workflows = await this.getWorkflows();
            workflows[workflowId] = workflow;
            
            const result = await this.saveToGitee('data/workflows.json', workflows);
            if (result.success) {
                this.saveToCache('workflows', workflows);
                this.emit('dataChanged', { type: 'workflows', data: workflows });
            }
            
            return result;
        } catch (error) {
            console.error('保存流程失败:', error);
            return { success: false, message: error.message };
        }
    }
    
    /**
     * 删除流程配置
     */
    async deleteWorkflow(workflowId) {
        try {
            const workflows = await this.getWorkflows();
            
            if (!workflows[workflowId]) {
                return { success: false, message: '流程不存在' };
            }
            
            delete workflows[workflowId];
            
            const result = await this.saveToGitee('data/workflows.json', workflows);
            if (result.success) {
                this.saveToCache('workflows', workflows);
                this.emit('dataChanged', { type: 'workflows', data: workflows });
            }
            
            return result;
        } catch (error) {
            console.error('删除流程失败:', error);
            return { success: false, message: error.message };
        }
    }
    
    /**
     * 获取需求类型配置
     */
    async getDemandTypes() {
        let demandTypes = this.loadFromCache('demandTypes');
        if (!demandTypes) {
            demandTypes = await this.loadFromGitee('data/demand-types.json') || this.getDefaultData('demandTypes');
            this.saveToCache('demandTypes', demandTypes);
        }
        return demandTypes;
    }
    
    /**
     * 获取紧急度配置
     */
    async getUrgencyLevels() {
        let urgencyLevels = this.loadFromCache('urgencyLevels');
        if (!urgencyLevels) {
            urgencyLevels = await this.loadFromGitee('data/urgency-levels.json') || this.getDefaultData('urgencyLevels');
            this.saveToCache('urgencyLevels', urgencyLevels);
        }
        return urgencyLevels;
    }
    
    /**
     * 获取用户列表
     */
    async getUsers() {
        let users = this.loadFromCache('users');
        if (!users) {
            users = await this.loadFromGitee('data/users.json') || this.getDefaultData('users');
            this.saveToCache('users', users);
        }
        return users;
    }
    
    /**
     * 添加用户
     */
    async addUser(user) {
        try {
            const users = await this.getUsers();
            
            // 生成ID
            if (!user.id) {
                user.id = `user_${Date.now()}`;
            }
            
            // 设置创建时间
            user.createdAt = new Date().toISOString();
            user.lastLogin = null;
            user.isActive = true;
            
            users.push(user);
            
            const result = await this.saveToGitee('data/users.json', users);
            if (result.success) {
                this.saveToCache('users', users);
                this.emit('dataChanged', { type: 'users', data: users });
            }
            
            return result;
        } catch (error) {
            console.error('添加用户失败:', error);
            return { success: false, message: error.message };
        }
    }
    
    /**
     * 更新用户
     */
    async updateUser(updatedUser) {
        try {
            const users = await this.getUsers();
            const index = users.findIndex(u => u.id === updatedUser.id);
            
            if (index === -1) {
                return { success: false, message: '用户不存在' };
            }
            
            users[index] = { ...users[index], ...updatedUser };
            
            const result = await this.saveToGitee('data/users.json', users);
            if (result.success) {
                this.saveToCache('users', users);
                this.emit('dataChanged', { type: 'users', data: users });
            }
            
            return result;
        } catch (error) {
            console.error('更新用户失败:', error);
            return { success: false, message: error.message };
        }
    }
    
    /**
     * 删除用户
     */
    async deleteUser(userId) {
        try {
            const users = await this.getUsers();
            const filteredUsers = users.filter(u => u.id !== userId);
            
            if (filteredUsers.length === users.length) {
                return { success: false, message: '用户不存在' };
            }
            
            const result = await this.saveToGitee('data/users.json', filteredUsers);
            if (result.success) {
                this.saveToCache('users', filteredUsers);
                this.emit('dataChanged', { type: 'users', data: filteredUsers });
            }
            
            return result;
        } catch (error) {
            console.error('删除用户失败:', error);
            return { success: false, message: error.message };
        }
    }
    
    /**
     * 获取系统配置
     */
    async getConfig() {
        let config = this.loadFromCache('config');
        if (!config) {
            config = await this.loadFromGitee('data/config.json') || this.getDefaultData('config');
            this.saveToCache('config', config);
        }
        return config;
    }
    
    /**
     * 同步所有数据
     */
    async syncAll() {
        return await this.syncFromCloud();
    }
    
    /**
     * 导出数据
     */
    async exportData() {
        try {
            const data = {
                demands: await this.getDemands(),
                workflows: await this.getWorkflows(),
                demandTypes: await this.getDemandTypes(),
                urgencyLevels: await this.getUrgencyLevels(),
                users: await this.getUsers(),
                config: await this.getConfig(),
                exportTime: new Date().toISOString()
            };
            
            const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            
            const a = document.createElement('a');
            a.href = url;
            a.download = `tasktrack_backup_${new Date().toISOString().split('T')[0]}.json`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            
            return { success: true };
        } catch (error) {
            console.error('导出数据失败:', error);
            return { success: false, message: error.message };
        }
    }
    
    /**
     * 导入数据
     */
    async importData(file) {
        return new Promise((resolve) => {
            const reader = new FileReader();
            reader.onload = async (e) => {
                try {
                    const data = JSON.parse(e.target.result);
                    
                    // 验证数据格式
                    const requiredKeys = ['demands', 'workflows', 'demandTypes', 'urgencyLevels', 'users'];
                    const hasAllKeys = requiredKeys.every(key => data.hasOwnProperty(key));
                    
                    if (!hasAllKeys) {
                        resolve({ success: false, message: '数据格式不正确' });
                        return;
                    }
                    
                    // 保存数据
                    const savePromises = [
                        this.saveToGitee('data/demands.json', data.demands),
                        this.saveToGitee('data/workflows.json', data.workflows),
                        this.saveToGitee('data/demand-types.json', data.demandTypes),
                        this.saveToGitee('data/urgency-levels.json', data.urgencyLevels),
                        this.saveToGitee('data/users.json', data.users)
                    ];
                    
                    if (data.config) {
                        savePromises.push(this.saveToGitee('data/config.json', data.config));
                    }
                    
                    const results = await Promise.all(savePromises);
                    const allSuccess = results.every(r => r.success);
                    
                    if (allSuccess) {
                        // 更新本地缓存
                        this.saveToCache('demands', data.demands);
                        this.saveToCache('workflows', data.workflows);
                        this.saveToCache('demandTypes', data.demandTypes);
                        this.saveToCache('urgencyLevels', data.urgencyLevels);
                        this.saveToCache('users', data.users);
                        if (data.config) {
                            this.saveToCache('config', data.config);
                        }
                        
                        this.emit('dataChanged', { type: 'all', data: data });
                        resolve({ success: true });
                    } else {
                        const failedResults = results.filter(r => !r.success);
                        resolve({ success: false, message: `部分数据导入失败: ${failedResults.map(r => r.message).join(', ')}` });
                    }
                } catch (error) {
                    console.error('导入数据失败:', error);
                    resolve({ success: false, message: error.message });
                }
            };
            
            reader.onerror = () => {
                resolve({ success: false, message: '文件读取失败' });
            };
            
            reader.readAsText(file);
        });
    }
    
    /**
     * 清空本地数据
     */
    clearLocalData() {
        try {
            const keys = ['demands', 'workflows', 'demandTypes', 'urgencyLevels', 'users', 'config'];
            keys.forEach(key => {
                localStorage.removeItem(`tasktrack_${key}`);
                this.cache.delete(key);
            });
            
            this.emit('dataChanged', { type: 'all', data: null });
            return { success: true };
        } catch (error) {
            console.error('清空本地数据失败:', error);
            return { success: false, message: error.message };
        }
    }
    
    /**
     * 事件监听
     */
    addEventListener(event, callback) {
        if (!this.eventListeners.has(event)) {
            this.eventListeners.set(event, []);
        }
        this.eventListeners.get(event).push(callback);
    }
    
    /**
     * 移除事件监听
     */
    removeEventListener(event, callback) {
        if (this.eventListeners.has(event)) {
            const listeners = this.eventListeners.get(event);
            const index = listeners.indexOf(callback);
            if (index > -1) {
                listeners.splice(index, 1);
            }
        }
    }
    
    /**
     * 触发事件
     */
    emit(event, data) {
        if (this.eventListeners.has(event)) {
            this.eventListeners.get(event).forEach(callback => {
                try {
                    callback(data);
                } catch (error) {
                    console.error(`事件监听器执行失败 (${event}):`, error);
                }
            });
        }
    }
}

// 创建全局数据管理器实例
window.dataManager = new DataManager();